
// storeListen.ts
class StoreListen {
    old = {} as Record<string, any>
    timer = 0 as any
    constructor() {
        this.old = this.getAllSore()

        window.addEventListener('visibilitychange', () => {
            if (document.visibilityState === 'hidden') {
                console.log('页面已隐藏')
                this.old = this.getAllSore()
            } else if (document.visibilityState === 'visible') {
                console.log('页面已显示')
                this.loopFn()
            }
        })
    }

    getAllSore() {
        return JSON.parse(JSON.stringify(localStorage))
    }

    difKeys() {
        const newStore = this.getAllSore()
        const difKeys: string[] = []
        const { old } = this
        Object.entries(newStore).forEach(([k, v]) => {
            const newV = typeof v === 'object' ? JSON.stringify(v) : v + ''
            const oldV = typeof old[k] === 'object' ? JSON.stringify(old[k]) : old[k] + ''
            if (newV !== oldV) difKeys.push(k)
        })
        this.old = newStore
        return difKeys
    }

    loopFn() {
        const difKeys = this.difKeys()
        if (difKeys.length) {
            window.dispatchEvent(new CustomEvent('localStoreChange', { detail: difKeys }))
        }
    }

    startLoop() {
        this.stopLoop()
        this.timer = setInterval(() => this.loopFn(), 300)
    }

    stopLoop() {
        clearInterval(this.timer)
    }
}

export default new StoreListen()


// main.ts
import './storeListen'


// .vue文件中使用
type LocalStoreChange = {
    detail: string[]
}
window.addEventListener('localStoreChange', (e) => {
    console.error('我是自定义时间', (e as any as LocalStoreChange).detail)
    const { detail } = e as any as { detail: string[] }
    if (detail.includes('a')) {
        console.log('我改刷新了')
    }
})